package com.royal.lr.util;


import com.royal.lr.annotation.NotMapping;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

public class ReflectUtil {

    public static void setFieldVal(Object obj, Map<String, String> valMap) throws Exception {
        Class tClass = obj.getClass();
            for (String key : valMap.keySet()) {
                String value=valMap.get(key);
               setSingleFieldVal(obj,key,value);
            }
    }

    public static void setSingleFieldVal(Object obj, String name,Object value) throws Exception {
        if(value!=null){
            Class tClass = obj.getClass();
            PropertyDescriptor pd = new PropertyDescriptor(name, tClass);
            //获得set方法
            Method method = pd.getWriteMethod();
            method.invoke(obj, value);
        }
    }

    public static void setTargetVal(Object source, Object target,Object mappingObj) throws Exception {
        Class sourceClass = source.getClass();
        Field[] fields = sourceClass.getDeclaredFields();
        for(Field field:fields){
            NotMapping notMapping=field.getAnnotation(NotMapping.class);
            if(notMapping!=null)continue;
            String fieldName=field.getName();
           String attributeVal= (String) getFieldVal(source,fieldName);
            if(attributeVal!=null){
                String value= String.valueOf(getFieldVal(mappingObj,attributeVal));
                setSingleFieldVal(target,fieldName,value);
            }
        }

    }

    public static Object getFieldVal(Object obj,String fieldName)throws Exception{
        Class clazz=obj.getClass();
        PropertyDescriptor pd = new PropertyDescriptor(fieldName, clazz);
        //获得get方法
        Method get = pd.getReadMethod();
        Object value = get.invoke(obj);
        return value;
    }
}
